<?php
namespace app\Index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;
use think\exception\HttpException;
use app\index\model\User;
class Base extends Controller
{
    //继承了\think\Controller，可以定义初始化方法_initialize，在该控制器的方法调用之前首先执行。
    public function _initialize()
    {
        //自动登录
        if(Cookie::has("user_name")){
            $username = encry_code(Cookie::get("user_name"),"DECODE");
            $password = encry_code(Cookie::get("user_psk"),"DECODE");
            $admin = new User();
            $userinfo = $admin -> login($username,$password);//后台密码验证
            if(!empty($userinfo)){
                if($userinfo['upass'] == $password){
                    Session::set('user_id',$userinfo['uid']);
                    Session::set('user_name',$userinfo['uname']);
                    Session::set('user_nik',$userinfo['unik']);
                    Session::set('user_role',$userinfo['urole']);
                    Session::set('last_time',time()+1800);//1800
                    Cookie::set('user_id', encry_code($userinfo['uid']), 604800);
                    Cookie::set('user_name', encry_code($userinfo['uname']), 604800);
                    Cookie::set('user_psk', encry_code($userinfo['upass']), 604800);
                }
            }
        }
        //判断用户是否登录
        if(!Session::get("user_name")){
            //return $this -> error("您还没有登录，请先登录...",url("Login/login"), "", 1);
            return $this -> redirect("Login/login");
        }
        //登录超时判断
        if((Session::get("last_time") - time()) <= 0){
            if (Request::instance()->isAjax()){
                // 抛出 HTTP 异常
                throw new HttpException(900, 'timeout', null, [url("Login/login")]);
            }
            //return $this -> error("由于长时间没有动作，系统已自动退出...",url("Login/login"), "", 1);
            return $this -> redirect("Login/login");
        }
        //用户执行操作，延长过期时间
        if(Session::has("last_time")){
            Session::set('last_time',time()+1800);
        }
    }
}